{% extends "../base.html" %}

<!-- =================================================================== -->
<!-- Page onload ======================================================= -->
<!-- =================================================================== -->
{% block BaseHead %}
<script type="text/javascript">
GW.pageOnLoad = function() {
    GW.div.fullscreen( "idBB" );
    GW.initMarkerTable();
    GW.initNewMarkerDialog();
    var oPB1 = new YAHOO.widget.Button("idNewMarkerBtn", { onclick: { fn: GW.newMarker } });
    GW.wait.hide();
    GW.log.log( 'admin/markers.html init' );
};
GW.initMarkerTable = function(){
    // Setup data source
    GW.src = new YAHOO.util.XHRDataSource("/gw/json/markers");
    GW.src.responseType = YAHOO.util.DataSource.TYPE_JSON;
    GW.src.connXhrMode = "queueRequests";
    GW.src.responseSchema = { resultsList: "markers", 
                              fields: ["name"] };
    // Setup data table
    YAHOO.widget.DataTable.Formatter.marker = GW.markerFormatter;
    GW.col = [
        // Actual data fields
        {key: "name", label: 'Name', sortable:true, resizeable:true, minWidth:200},
        {key: "marker", label: 'Marker', sortable:false, resizeable:true, minWidth:50,
            formatter:"marker"
        },
        // Action icons:
        // The action property is borrowed from Satyam.  It is used to customize
        // the behavior of these column to an onclick event.
        {key:'delete', label:'Delete', className: 'delete-row', action: 'delete'}
    ];
    GW.dt = new YAHOO.widget.DataTable( "idTable", GW.col, GW.src );
    // Set up datatable editing flow
    GW.dt.subscribe("cellMouseoverEvent", GW.dt.onEventHighlightCell);
    GW.dt.subscribe("cellMouseoutEvent", GW.dt.onEventUnhighlightCell);
    GW.dt.subscribe("cellClickEvent", GW.markerDelete );
};
// Custom cell formater for marker images
GW.markerFormatter = function( elCell, oRecord, oColumn, oData){
    var name = oRecord.getData('name');
    var src = '<img src="/gw/json/marker/' + name + '">';
    elCell.innerHTML = '&nbsp;' + src;
};
// Init new marker dialog
GW.initNewMarkerDialog = function(){
    // Create and render the dialog
    GW.markerDialogConfig = {
        postmethod: "none",
        fixedcenter : true,
        visible : false, 
        hideaftersubmit: true,
        constraintoviewport: true,
        modal: true,
        buttons : [ { text:"Cancel", handler:GW.newMarkerCancel, isDefault:true },
                    { text:"Save", handler:GW.newMarkerSave }]
    };
    GW.markerDialog = new YAHOO.widget.Dialog("idMarkerDialog", GW.markerDialogConfig );
    GW.markerDialog.render(document.body);
};
// Handle marker delete 
GW.markerDelete = function(oArgs){
    var target = oArgs.target;
    var column = this.getColumn(target);
    var row = this.getRow(target);
    var record = this.getRecord( row );
    var name = record.getData('name');
    // Columns with action icons should have an action property
    // The action property, not the visual image, determins the action.
    switch (column.action) {
        // For the delete action request user confirmation and call the ask method of the DataSource
        case 'delete':
            if (confirm('Are you sure you want to delete ' + name + '?')) { 
                // send delete to server
                // Send delete to the GeoWiki server
                var callback = {
                    failure: function(o){
                        var msg = 'Marker delete failed. Status:' + o.status + ' Text:' + o.statusText;
                        GW.log.log( msg, 'error', 'admin/markers' );
                        alert( 'Marker delete failed.  Check log!' );
                    },
                    success: function(o){
                        var msg = 'Marker delete succeeded. Status:' + o.status + ' Text:' + o.statusText;
                        GW.log.log( msg, 'info', 'admin/markers' );
                        alert( 'Marker delete successful.' );
                        this.deleteRow( row ); 
                        },
                    scope: this,
                    timeout: 10000
                };
                var uri = '/gw/json/marker/' + name;
                var request = YAHOO.util.Connect.asyncRequest( 'DELETE', uri, callback );
            }
            break;
        }
};
// New marker 
GW.newMarker = function(){
    GW.markerDialog.bringToTop();
    GW.markerDialog.show();
};
// Cancel a new marker
GW.newMarkerCancel = function( click, dialog ){
    dialog.cancel();
};
// Upload new marker handler
GW.newMarkerUpload = function( o, dialog ){
    // The browser may wrap the JSON response in <pre> </pre>
    var text = o.responseText;
    var jsontext = text.match(/\{.*\}/)[0];
    var o = YAHOO.lang.JSON.parse( jsontext );
    if( !o.success ){
        alert( 'Upload failed.' );
        GW.log.log( jsontext, 'error', 'admin/markers' );
        return;
    }
    alert( 'Upload succeeded as a ' + o.operation + '. Name ' + o.name );
    marker = { name: o.name };
    GW.dt.addRow(marker);
};
// Save a new marker
GW.newMarkerSave = function( click, dialog ){
    // Post to the GeoWiki server
    var callback = {
        failure: function(o){
            var msg = 'Marker save failed. Status:' + o.status + ' Text:' + o.statusText;
            GW.log.log( msg, 'error', 'admin/markers' );
            alert( 'Failure, see log' );
        },
        upload: function(o){GW.newMarkerUpload( o, dialog );},
        timeout: 10000
    };
    // get the file name
    YAHOO.util.Connect.setForm( 'idNewMarker', true);
    // Various browsers return different values for the filename of a type="file"
    // FF returns filename.ext
    // IE returns fullpath/filename.ext
    // Here isolate the simple file name, ex. filename.ext
    var iName = dialog.form.img.value;
    var sName = iName.match(/[^\/\\]+$/);                                       //  /\w+\.\w+$/
    dialog.form.filename.value = sName;
    var request = YAHOO.util.Connect.asyncRequest( 'POST', '/gw/json/marker', callback );
    dialog.cancel();
};
</script>
{% endblock %}

<!-- =================================================================== -->
<!-- Page body ========================================================= -->
<!-- =================================================================== -->
{% block BaseBody %}
<style type="text/css">
    .delete-row {
        cursor:pointer;
        background: transparent url(/static/img/deleterow.png) no-repeat center center;
        width:16px;height:16px;
    }
    .markerLabel { 
        display:block;
        float:left;
        width: 15em;
        padding-right: 0.5em;
        font-size: 80%;
        clear:left; 
        margin-bottom: 0.5em;
    }
    .markerInput {
        margin-bottom: 0.5em;
    }
</style>

<div id="idBB" style="overflow: auto;" >
    <div style="padding-left: 0.5em; padding-top: 0.5em;">
        <input type="button" id="idNewMarkerBtn" name="newMarkerButton" value="New marker">
        <p><br />To edit an existing marker click the table row.<br /><b>NOTE:</b> 
        Modifications to the markers take place <b>IMMEDIATELY.</b></p>
        <p>Markers should be 32x32 with a transparent background.</p>
        <p>Marker names <b>MUST</b> be legal URI names, ex: markerimage.png, markerimage.jpeg, etc.</p>
        <p>&nbsp;</p>
        <div id='idTable'><!-- data table goes here --></div>
        &nbsp;
        &nbsp;
    </div>
</div>

<!-- =================================================================== -->
<!-- Marker dialog allows editing of marker information and deletion of  -->
<!-- markers.                                                            -->
<!-- =================================================================== -->
<div id="idMarkerDialog" style="visibility:hidden">
    <div class="hd">Please enter marker information</div>
    <div class="bd">
        <form id="idNewMarker" method="post" enctype="multipart/form-data" action="/gw/json/markers" name="Form1">
            <div class="clear"></div>
            <label for="img" class="markerLabel" >Marker source:</label>
            <input class="markerInput" type="file" name="img" value="" size="50" />
            <input type="hidden" name="filename" value="" style="width: 30em; " />
            <div class="clear"></div>
            <label for="name" class="markerLabel" >Marker name, ex marker.png:<br /><b>Name must be unique and contain correct extension</b>.</label>
            <input class="markerInput" type="text" name="name" value="" size="20" />
            <div class="clear"></div>
            <label for "reset" class="markerLabel">Reset:</label>
            <input class="markerInput" type="Reset" name="reset">
        </form>
    </div>
</div>
{% endblock %}


